<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部标题栏 -->
    <div class="bg-white shadow-sm">
      <div class="container mx-auto px-6 py-4 flex justify-between items-center">
        <h1 class="text-3xl font-bold text-gray-800">月度账单结算</h1>
        <div class="flex items-center">
          <el-date-picker
              v-model="currentMonth"
              type="month"
              placeholder="选择月份"
              class="w-48"
              @change="fetchBillData"
          />
          <el-button
              type="primary"
              class="!rounded-button whitespace-nowrap ml-4"
              @click="speakBill"
          >
            <el-icon class="mr-2"><i class="fas fa-volume-up" /></el-icon>
            语音播报
          </el-button>
        </div>
      </div>
    </div>
    <!-- 主要内容区 -->
    <div class="container mx-auto px-6 py-8">
      <!-- 账单总览卡片 -->
      <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <div class="flex flex-col md:flex-row">
          <div class="md:w-1/2 mb-6 md:mb-0">
            <h2 class="text-2xl font-semibold text-gray-700 mb-4">本月账单总览</h2>
            <div class="flex items-end mb-4">
              <span class="text-5xl font-bold text-blue-600 mr-2">¥{{ totalAmount }}</span>
            </div>
          </div>
          <div class="md:w-1/2 h-64">
            <div ref="pieChart" class="w-full h-full"></div>
          </div>
        </div>
      </div>
      <!-- 费用趋势图表 -->
      <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <h2 class="text-2xl font-semibold text-gray-700 mb-4">费用趋势分析</h2>
        <div ref="lineChart" class="w-full h-80"></div>
      </div>
      <!-- 费用分类模块 -->
      <div class="space-y-6">
        <!-- 餐饮账单 -->
        <el-card class="rounded-xl">
          <template #header>
            <div class="flex justify-between items-center">
              <div class="flex items-center">
                <el-icon class="text-orange-500 mr-3"><i class="fas fa-utensils" /></el-icon>
                <span class="text-xl font-semibold"
                      @click="showMealDetails = !showMealDetails"
                >
                  餐饮账单
                </span>
              </div>
              <div class="flex items-center">
                <span class="text-xl font-bold text-gray-800 mr-4">¥{{ orderTotal }}</span>
              </div>
            </div>
          </template>
          <el-collapse-transition>
            <div v-show="showMealDetails">
              <el-table :data="billData.order" style="width: 100%">
                <el-table-column prop="id" label="订单号" width="200" />
                <el-table-column prop="date" label="预定时间" width="200" />
                <el-table-column prop="totalAmount" label="总价" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ row.totalAmount }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-transition>
        </el-card>
        <!-- 住宿费用 -->
        <el-card class="rounded-xl">
          <template #header>
            <div class="flex justify-between items-center">
              <div class="flex items-center">
                <el-icon class="text-blue-500 mr-3"><i class="fas fa-bed" /></el-icon>
                <span class="text-xl font-semibold">住宿费用</span>
              </div>
              <div class="flex items-center">
                <span class="text-xl font-bold text-gray-800 mr-4">¥{{ roomTotal }}</span>
                <el-icon
                    :class="{ 'transform rotate-180': showAccommodationDetails }"
                    class="cursor-pointer transition-transform duration-300"
                    @click="showAccommodationDetails = !showAccommodationDetails"
                >
                  <i class="fas fa-chevron-down" />
                </el-icon>
              </div>
            </div>
          </template>
          <el-collapse-transition>
            <div v-show="showAccommodationDetails">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <div class="flex items-center mb-2">
                    <el-icon class="text-blue-500 mr-2"><House /></el-icon>
                    <span class="text-gray-600">房间号</span>
                  </div>
                  <p class="text-lg font-medium">{{ billData.room.rno }}</p>
                </div>
                <div>
                  <div class="flex items-center mb-2">
                    <el-icon class="text-blue-500 mr-2"><OfficeBuilding /></el-icon>
                    <span class="text-gray-600">房型</span>
                  </div>
                  <p class="text-lg font-medium">{{ billData.room.type === 1? '单人间': '双人间'}}</p>
                </div>
                <div>
                  <div class="flex items-center mb-2">
                    <el-icon class="text-blue-500 mr-2"><Calendar /></el-icon>
                    <span class="text-gray-600">房间账单</span>
                  </div>
                  <p class="text-lg font-medium">{{ billData.room.rmoney }}</p>
                </div>
              </div>
            </div>
          </el-collapse-transition>
        </el-card>
        <!-- 护理费用 -->
        <el-card class="rounded-xl">
          <template #header>
            <div class="flex justify-between items-center">
              <div class="flex items-center">
                <el-icon class="text-green-500 mr-3"><i class="fas fa-hand-holding-medical" /></el-icon>
                <span class="text-xl font-semibold">护理费用</span>
              </div>
              <div class="flex items-center">
                <span class="text-xl font-bold text-gray-800 mr-4">¥{{ reServiceTotal }}</span>
                <el-icon
                    :class="{ 'transform rotate-180': showCareDetails }"
                    class="cursor-pointer transition-transform duration-300"
                    @click="showCareDetails = !showCareDetails"
                >
                  <i class="fas fa-chevron-down" />
                </el-icon>
              </div>
            </div>
          </template>
          <el-collapse-transition>
            <div v-show="showCareDetails">
              <el-table :data="billData.reService" style="width: 100%">
                <el-table-column prop="service.name" label="护理项目" width="200" />
                <el-table-column prop="service.frequency" label="次数" width="120" />
                <el-table-column prop="service.price" label="单价" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ row.service.price }}
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="金额" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ row.totalPrice }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-transition>
        </el-card>
      </div>
    </div>
    <!-- 底部操作栏 -->
    <div class="fixed bottom-0 left-0 right-0 bg-white shadow-lg py-4 px-6">
      <div class="container mx-auto flex justify-end space-x-4">
        <el-button
            type="info"
            class="!rounded-button whitespace-nowrap"
            @click="printBill"
        >
          <el-icon class="mr-2"><i class="fas fa-print" /></el-icon>
          打印账单
        </el-button>
        <el-button
            type="primary"
            class="!rounded-button whitespace-nowrap"
            @click="payBill"
        >
          <el-icon class="mr-2"><i class="fas fa-credit-card" /></el-icon>
          支付账单
        </el-button>
      </div>
    </div>
  </div>
</template>
<script lang="js" setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import accountApiUser from "@/api/user/accountApiUser.js";
import roomApi from "@/api/admin/roomApi.js";
import {useUserStore} from "@/stores/user.js";
import {Calendar, House, OfficeBuilding, Warning} from "@element-plus/icons-vue";

const userStore = useUserStore();
// 当前月份
const currentMonth = ref(new Date());
// 账单数据
const billData = ref({
  order:[],
  reService:[],
  room:[]
});
// 计算属性
const orderTotal = computed(() => {
  let count = 0;
  billData.value.order.forEach(item => {
    count += item.totalAmount;
  });
  return count;
});
const reServiceTotal = computed(() =>{
  let count = 0;
  billData.value.reService.forEach(item => {
    count += item.totalPrice;
  });
  return count;
});
const roomTotal = computed(() => {
  let count = 0;
  count += billData.value.room.rmoney
  return count;
});
const totalAmount = computed(() => orderTotal.value + reServiceTotal.value + roomTotal.value);
// 明细显示控制
const showMealDetails = ref(false);
const showAccommodationDetails = ref(false);
const showCareDetails = ref(false);
// 图表引用
const pieChart = ref();
const lineChart = ref();

// 初始化图表
const initCharts = () => {
  if (!pieChart.value || !lineChart.value) return;
// 饼图
  const pieChartInstance = echarts.init(pieChart.value);
  pieChartInstance.setOption({
    animation: false,
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['餐饮', '住宿', '护理'],
    },
    series: [
      {
        name: '费用占比',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: orderTotal.value, name: '餐饮', itemStyle: { color: '#FF9F43' } },
          { value: roomTotal.value, name: '住宿', itemStyle: { color: '#546DE5' } },
          { value: reServiceTotal.value, name: '护理', itemStyle: { color: '#3DC1D3' } },
        ],
      },
    ],
  });
// 折线图
  const lineChartInstance = echarts.init(lineChart.value);
  lineChartInstance.setOption({
    animation: false,
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['餐饮', '住宿', '护理', '总计'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '餐饮',
        type: 'line',
        stack: '总量',
        data: [500, 550, 560, 600, orderTotal.value],
        itemStyle: { color: '#FF9F43' },
      },
      {
        name: '住宿',
        type: 'line',
        stack: '总量',
        data: [599, 599, 599, 500, reServiceTotal.value],
        itemStyle: { color: '#546DE5' },
      },
      {
        name: '护理',
        type: 'line',
        stack: '总量',
        data: [1000, 1000, 1100, 1200, roomTotal.value],
        itemStyle: { color: '#3DC1D3' },
      },
      {
        name: '总计',
        type: 'line',
        data: [2200, 2100, 2200, 2300, totalAmount.value],
        itemStyle: { color: '#F78FB3' },
      },
    ],
  });
// 窗口大小变化时重新调整图表大小
  window.addEventListener('resize', () => {
    pieChartInstance.resize();
    lineChartInstance.resize();
  });
};
// 获取账单数据
const fetchBillData = () => {
// 模拟API请求
  console.log('Fetching bill data for:', currentMonth.value);
// 这里实际应该发送请求获取数据
// 数据获取完成后重新渲染图表
  nextTick(() => {
    initCharts();
  });
};
// 语音播报
const speakBill = () => {
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance();
    utterance.text = `本月账单总金额为${totalAmount.value}元，其中餐饮费用${orderTotal.value}元，住宿费用${reServiceTotal.value}元，护理费用${roomTotal.value}元。`;
    window.speechSynthesis.speak(utterance);
  } else {
    ElMessage.warning('您的浏览器不支持语音播报功能');
  }
};
// 打印账单
const printBill = () => {
  window.print();
};
// 支付账单
const payBill = () => {
  accountApiUser.pay().then(resp => {
    if (resp.code === 10000){
      ElMessage.success('账单支付成功');
    }
  })
};

// 获取餐饮账单
const selectByOrder = () => {
  accountApiUser.selectByOrder().then(resp => {
    if (resp.code === 10000){
      billData.value.order = resp.data
      initCharts();
    }
  })
}
// 获取护理账单
const selectByReService = () => {
  accountApiUser.selectByReService().then(resp => {
    if (resp.code === 10000){
      billData.value.reService = resp.data
      initCharts();
    }
  })
}
// 获取房间账单
const selectByRoom = () =>{
  let id = userStore.userInfo.rid;
  roomApi.selectById(id)
      .then(resp => {
        if (resp.code === 10000){
          billData.value.room = resp.data
          initCharts();
        }
      })
}

selectByOrder();
selectByReService();
selectByRoom();

</script>
<style scoped>
/* 增大字体 */
.text-3xl {
  font-size: 2rem;
}
.text-2xl {
  font-size: 1.75rem;
}
.text-xl {
  font-size: 1.5rem;
}
.text-lg {
  font-size: 1.25rem;
}
/* 高对比度配色 */
.text-blue-600 {
  color: #2563eb;
}
.text-green-500 {
  color: #10b981;
}
.text-red-500 {
  color: #ef4444;
}
/* 按钮样式增强 */
.el-button {
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
}
/* 表格样式调整 */
.el-table {
  font-size: 0.9rem;
}
.el-table .el-table__expanded-cell {
  padding: 0;
}
.el-table .el-table__expanded-cell .el-table {
  background-color: #f8fafc;
}
.el-table .el-table__expanded-cell .el-table::before {
  display: none;
}
.el-table th {
  font-weight: bold;
}
.el-table td {
  padding: 8px 0;
}
.el-table .el-table__body-wrapper {
  max-height: 500px;
  overflow-y: auto;
}
/* 卡片样式调整 */
.el-card {
  margin-bottom: 1.5rem;
}
.el-card__header {
  padding: 1.25rem 1.5rem;
  font-size: 1.25rem;
}
/* 底部操作栏固定 */
.fixed {
  z-index: 1000;
}
.detail-table-container {
  max-width: 100%;
  padding: 0 1rem;
}

</style>
